import { Form, Space, Button, Row, Col } from 'antd'
import './index.less'
import { Fragment, useState, useLayoutEffect, useEffect } from 'react'
import getComponents from './ComponentType'
import { useForm } from 'antd/es/form/Form'
import { DownOutlined, UpOutlined } from '@ant-design/icons'
import { ISearchProps } from './types'
export default function SearchForm(props: ISearchProps) {
  const [form] = useForm()
  const maxSpan = 24
  const slicedNum = 2
  const grid = { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 6 }
  const [isFold, setIsFold] = useState(props.isFold ? props?.isFold : false) //默认是折叠状态
  const [currentSpan, setCurrentSpan] = useState(8) //默认一行展示24/8=3个
  const [handledSearchConfig, sethandledSearchConfig] = useState<IItemArray[]>([])
  const reCalcHeight = () => {
    const searchConfig = props.searchConfig?.filter((item) => !item.hidden)
    if (window.innerWidth < 768) {
      setCurrentSpan(24)
    } else if (window.innerWidth >= 768 && window.innerWidth < 992) {
      if (isFold) {
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.md) === 0) setCurrentSpan(24)
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.md) === 1) setCurrentSpan(12)
      } else {
        if (searchConfig.length % (maxSpan / grid.md) === 0) setCurrentSpan(24)
        if (searchConfig.length % (maxSpan / grid.md) === 1) setCurrentSpan(12)
      }
    } else if (window.innerWidth >= 992 && window.innerWidth < 1600) {
      if (isFold) {
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 0) setCurrentSpan(24)
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 1) setCurrentSpan(16)
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.lg) === 2) setCurrentSpan(8)
      } else {
        if (searchConfig.length % (maxSpan / grid.lg) === 0) setCurrentSpan(24)
        if (searchConfig.length % (maxSpan / grid.lg) === 1) setCurrentSpan(16)
        if (searchConfig.length % (maxSpan / grid.lg) === 2) setCurrentSpan(8)
      }
    } else {
      if (isFold) {
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 0) setCurrentSpan(24)
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 1) setCurrentSpan(18)
        if (searchConfig.slice(0, slicedNum).length % (maxSpan / grid.xxl) === 2) setCurrentSpan(12)
      } else {
        if (searchConfig.length % (maxSpan / grid.xxl) === 0) setCurrentSpan(24)
        if (searchConfig.length % (maxSpan / grid.xxl) === 1) setCurrentSpan(18)
        if (searchConfig.length % (maxSpan / grid.xxl) === 2) setCurrentSpan(12)
        if (searchConfig.length % (maxSpan / grid.xxl) === 3) setCurrentSpan(6)
      }
    }
  }
  useEffect(() => {
    const handledSearchConfig = props.searchConfig
      ?.filter((item) => !item.hidden)
      ?.map((item) => {
        if (item?.config?.onClear && typeof item?.config?.onClear === 'function') {
          return {
            ...item,
            config: {
              ...item?.config,
              onClear: (...set: any) => {
                item?.config?.onClear(...set)
                if (props.params != null && item.name) {
                  Reflect.deleteProperty(props.params, item.name)
                }
              },
            },
          }
        } else {
          if (['Input']?.includes(item.type)) {
            return {
              ...item,
            }
          } else {
            return {
              ...item,
              config: {
                ...item?.config,
                onClear: () => {
                  if (props.params != null && item.name) {
                    Reflect.deleteProperty(props.params, item.name)
                  }
                },
              },
            }
          }
        }
      })
    sethandledSearchConfig(handledSearchConfig)
  }, [props.searchConfig])
  // 解决页面按钮位置的闪烁
  useLayoutEffect(() => {
    reCalcHeight()
    window.addEventListener('resize', debounce(reCalcHeight, 300))
    return () => {
      window.removeEventListener('resize', reCalcHeight)
    }
  }, [isFold])

  function isPass() {
    const formIns = props.form ? props.form : form
    const newValues: Record<string, string | number> = {}
    formIns.validateFields().then((values) => {
      Object.keys(values).forEach((key) => {
        if (values[key] || values[key] == 0) {
          newValues[key] = values[key]
        }
      })
      props.onFinish(newValues)
    })
  }

  function handleClickFold() {
    setIsFold(!isFold)
  }

  function debounce(fn: any, delay: number) {
    let timeout: ITimeoutType
    return (...set: any) => {
      if (timeout) clearTimeout(timeout)
      timeout = setTimeout(() => {
        fn(...set)
      }, delay)
    }
  }

  return (
    <div className={`search_form_wrap${props.className ? ' ' + props.className : ''}`}>
      <Form
        className="search_form_wrap_formbox"
        form={props.form ? props.form : form}
        labelAlign="right"
        layout="inline"
        labelWrap={true}
        onFinish={props.onFinish}
        initialValues={props?.initialValues}
        onValuesChange={props?.onValuesChange}
      >
        <Row gutter={[10, 10]}>
          {handledSearchConfig?.map((item, index) => {
            const isHidden = isFold && index >= slicedNum // 判断是否需要隐藏
            return (
              <Col {...grid} key={index} style={{ display: isHidden ? 'none' : 'block' }}>
                <Fragment>
                  <Form.Item {...item}>{item ? getComponents(item, isPass, index === 0) : null}</Form.Item>
                </Fragment>
              </Col>
            )
          })}
          <Col span={currentSpan}>
            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button type="primary" onClick={isPass}>
                  查询
                </Button>
                <Button onClick={props.onReset}>重置</Button>
                {props?.searchConfig?.length > 2 ? (
                  <Button type="link" onClick={handleClickFold}>
                    {isFold ? '更多筛选' : '收起'}
                    {isFold ? <DownOutlined /> : <UpOutlined />}
                  </Button>
                ) : null}
              </Space>
            </div>
          </Col>
        </Row>
      </Form>
      <div className="search_form_extra_wrap">{props?.extra}</div>
    </div>
  )
}
